package com.cmii.sjw.department.control.jsc.service.impl;

import com.cmii.sjw.department.control.common.RedisService;
import com.cmii.sjw.department.control.jsc.mapper.RoleCockpitMapper;
import com.cmii.sjw.department.control.jsc.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author jfh
 * @Date 2025年05月28日 10:40
 */
@Slf4j
@Service
public class MetricPermissionService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleCockpitMapper roleCockpitMapper;

    /**
     * 获取用户权限指标ID集合
     * @author jfh
     * @Date 2025/5/28 11:40
     * @param userId 用户ID
     * @return java.util.Set<java.lang.Long>
     */
    public Set<Long> getUserMetricIds(Long userId) {
        try {
            String cacheKey = "user:metrics:" + userId;
            Set<Long> metricIds = redisService.getCache(cacheKey, Set.class);
            // 缓存存在时直接返回（包含空集合）
            if (metricIds != null) {
                return metricIds;
            }

            List<Long> roleIds = userRoleMapper.selectRoleIdsByUserId(userId);
            if (CollectionUtils.isEmpty(roleIds)) {
                return Collections.emptySet();
            }
            metricIds = roleCockpitMapper.selectMetricIdsByRoleIds(roleIds);
            if (!metricIds.isEmpty()) {
                // 缓存30分钟
                redisService.setCache(cacheKey, metricIds, 60*30);
            }
            return metricIds;
        } catch (Exception e) {
            log.error("获取用户权限指标ID集合失败", e);
            return Collections.emptySet();
        }
    }
}
